import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Popconfirm, Button, Switch, Modal, Icon, Input, Upload, Radio, DatePicker } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './activity.css'
import moment from 'moment'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
const { TextArea } = Input
class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getActivityList: PropTypes.func,
    activityData: PropTypes.object,
    delActivity: PropTypes.func,
    delActivityRequest: PropTypes.any
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParam: {}
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.imageChange = this.imageChange.bind(this)
  }

  getFilterCols (category, author) {
    return [
      {
        label: '输入搜索',
        id: 'name',
        widget: widgetType.input,
        placeholder: '请输入活动编号/活动名称'
      }, {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <div className={Style['custom-buttons']}>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.search}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.reset}>重置</Button>
              <Button type='primary' onClick={this.handleAdd}>新建活动</Button>
            </div>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '活动编号',
        dataIndex: 'code',
        key: 'code',
        width: 100,
        sorter: (a, b) => a.code - b.code
      },
      {
        title: '活动名称',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 100
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: 100
      },
      {
        title: '上线/下线',
        dataIndex: 'time1',
        key: 'time1',
        width: 100,
        render: (text, record) => <Switch defaultChecked={text === 1} size='small' onChange={(e) => this.handleChange(e, record.id)} />
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'price',
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <div>
              <a className={Style['a-btn']} onClick={() => this.handleEdit(record)}>编辑</a>
              {/* <a className={Style['a-btn']}>发布到活动</a> */}
              <Popconfirm placement='top' title='确认是否还原' onConfirm={() => this.handleDel(record.id)}>
                <a className={Style['a-btn']}>删除</a>
              </Popconfirm>
            </div>
          </>
        },
        width: 100
      }
    ]
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    const { form } = this.props
    form.resetFields()
    this.props.getActivityList({
      pageNo: 1,
      pageSize: 20
    })
  }

  search () {
    const { pageSize, pageNo } = this.state
    let params = {
      pageSize, pageNo
    }
    // eslint-disable-next-line handle-callback-err
    this.props.form.validateFieldsAndScroll((err, values) => {
      params.name = values.name
      this.setState({
        params
      })
      this.props.getActivityList(params)
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getActivityList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getActivityList(params)
  }

  handleAdd () {
    this.setState({
      showModal: true,
      formStatus: 'add',
      title: '新建活动'
    })
  }

  handleEdit (editParam) {
    this.setState({
      showModal: true,
      formStatus: 'edit',
      title: '编辑活动',
      editParam
    })
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
  }

  handleChange (value, id) {
    this.props.changeActivityStatus({
      activityId: id,
      status: value ? 1 : 0
    })
  }

  // 删除
  handleDel (id) {
    this.props.delActivity({
      activityId: id
    })
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    let restoreList = []
    selectedRows && selectedRows.map(item => {
      restoreList.push(item.commodityId)
    })

    this.setState({
      restoreList,
      selectedRowKeys
    })
  }

  handleOk () {
    const { image, width, height, formStatus, editParam } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.startTime = values.startTime && values.startTime.format('YYYY-MM-DD HH:mm:ss')
        values.endTime = values.endTime && values.endTime.format('YYYY-MM-DD HH:mm:ss')
        values.image = image || values.image
        values.width = width || editParam.width
        values.height = height || editParam.height
        values.name = values.activityName
        if (formStatus === 'edit') {
          values.id = editParam.id
          this.props.editActivity(values)
        } else {
          this.props.createActivity(values)
        }
      }
    })
  }

  imageChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      if (file.response.success) {
        this.setState({
          loading: false,
          image: file.response && file.response.data.imageUrl,
          width: file.response && file.response.data.width,
          height: file.response && file.response.data.height
        })
      } else {
        message.error(file.response.msg)
        this.setState({
          loading: false
        })
      }
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getActivityList({
      pageSize,
      pageNo
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.delActivityRequest && nextProps.delActivityRequest) {
      message.success('删除成功')
      this.search()
    }
    if (!this.props.editActivityRequest && nextProps.editActivityRequest) {
      message.success('编辑成功')
      this.setState({
        showModal: false
      })
      this.search()
    }
    if (!this.props.createActivityRequest && nextProps.createActivityRequest) {
      message.success('新增成功')
      this.setState({
        showModal: false
      })
      this.search()
    }

    if (!this.props.activityStatusRequest && nextProps.activityStatusRequest) {
      message.success('操作成功')
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { pageNo, pageSize, selectedRowKeys, showModal, image, loading, editParam, title } = this.state
    const { form, activityData } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: activityData && activityData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    const uploadButton = (
      <div className={Style[`${image ? '' : 'image-container'}`]}>
        {
          (editParam.image || image) ? <div className={Style['banner-image']} style={{ backgroundImage: `url(${editParam.image || image})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset}
              actions={false}
            >
              {/* <Button type='primary' onClick={this.handleAdd}>新建活动</Button> */}
              {/* <Button onClick={this.handleDelAll}>批量删除</Button> */}
            </Filters>
            <CustomTable
              selectedRowKeys={selectedRowKeys}
              multipleSelect={this.onSelectChange}
              // multiple
              loading={!activityData} columns={this.getTableCols()}
              dataSource={(activityData && activityData.list) || []}
              pagination={pagination} />
            <Modal
              title={title}
              visible={showModal}
              width={600}
              onOk={this.handleOk}
              destroyOnClose
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label='活动标题'>
                  {getFieldDecorator('activityName', {
                    rules: [{ required: true, message: '请输入活动标题' }],
                    initialValue: editParam.name
                  })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='开始时间'>
                  {getFieldDecorator('startTime', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: editParam.startTime && moment(editParam.startTime)
                  })(
                    <DatePicker placeholder='请选择' />
                  )}
                </Form.Item>
                <Form.Item label='到期时间'>
                  {getFieldDecorator('endTime', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: editParam.endTime && moment(editParam.endTime)
                  })(
                    <DatePicker placeholder='请选择' />
                  )}
                </Form.Item>
                <Form.Item label='上线/下线'>
                  {getFieldDecorator('status', {
                    valuePropName: 'radio',
                    initialValue: editParam.status || 1
                  })(
                    <Radio.Group defaultValue={1}>
                      <Radio value={1}>上线</Radio>
                      <Radio value={0}>下线</Radio>
                    </Radio.Group>)}
                </Form.Item>
                <Form.Item label='活动图片' extra={<span style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.35)' }}>只能上传jpg/png格式，图片大小限定1～3M</span>}>
                  {getFieldDecorator('image', {
                    valuePropName: 'picture',
                    initialValue: image || editParam.image,
                    rules: [{ required: true, message: '请选上传banner图片' }]
                  })(
                    <Upload
                      action='/file/upload/1.0'
                      name='file'
                      onChange={this.imageChange}
                      showUploadList={false}
                      withCredentials
                      beforeUpload={this.beforeUpload}
                      headers={{
                        token: localStorage.getItem('token') || ''
                      }}
                    >
                      {uploadButton}
                      <Button type='primary'>
                        <Icon type='cloud-upload' /> 选择上传图片
                      </Button>
                    </Upload>
                  )}

                </Form.Item>
                <Form.Item label='活动内容'>
                  {getFieldDecorator('content', {
                    rules: [{ required: true, message: '请输入活动内容' }],
                    initialValue: editParam.content
                  })(
                    <TextArea placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='推送标题'>
                  {getFieldDecorator('pushTitle', {
                    rules: [{ required: true, message: '请输入推送标题' }],
                    initialValue: editParam.pushTitle
                  })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='推送标签'>
                  {getFieldDecorator('pushLabel', {
                    rules: [{ required: true, message: '请输入推送标签' }],
                    initialValue: editParam.pushLabel
                  })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='推送内容'>
                  {getFieldDecorator('pushContent', {
                    rules: [{ required: true, message: '请输入推送内容' }],
                    initialValue: editParam.pushContent
                  })(
                    <TextArea placeholder='请输入' />
                  )}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  activityData: state.operation.activityData,
  editActivityRequest: state.operation.editActivityRequest,
  createActivityRequest: state.operation.createActivityRequest,
  delActivityRequest: state.operation.delActivityRequest,
  activityStatusRequest: state.operation.activityStatusRequest
})
const mapDispatch = dispatch => ({
  getActivityList: dispatch.operation.getActivityList,
  delActivity: dispatch.operation.delActivity,
  createActivity: dispatch.operation.createActivity,
  editActivity: dispatch.operation.editActivity,
  changeActivityStatus: dispatch.operation.changeActivityStatus
})

const Index = Form.create()(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
